package com.yexuejc.vertx.todolist.verticle;


import com.yexuejc.base.http.Resps;
import com.yexuejc.base.util.JsonUtil;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

/**
 * @PackageName: com.yexuejc.vertx.todolist
 * @Description:
 * @author: maxf
 * @date: 2018/4/12 17:10
 */
public class RestfulApiVerticle extends AbstractVerticle {

    protected <T> void sendResponse(RoutingContext context, String address, Object params) {
        vertx.eventBus().send(
                address,// 消息地址
                params,// 消息内容
                result -> { // 异步结果处理
                    if (result.succeeded()) {
                        // 成功的话，返回处理结果给前台，这里的处理结果就是service返回的一段字符串
                        success(context, (String) result.result().body());
                    } else {
                        internalError(context, result.cause().getMessage());
                    }
                }
        );
    }

    /**
     * Send back a response with status 200 OK.
     *
     * @param context routing context
     * @param resps   message body
     */
    protected void success(RoutingContext context, Resps resps) {
        context.response().setStatusCode(200)
                .putHeader("content-type", "application/json")
                .end(JsonUtil.obj2Json(resps));
    }

    protected void success(RoutingContext context, String result) {
        context.response().setStatusCode(200)
                .putHeader("content-type", "application/json")
                .end(result);
    }

    /**
     * Send back a response with status 500 Internal Error.
     *
     * @param context routing context
     * @param resps   message body
     */
    protected void internalError(RoutingContext context, Resps resps) {
        context.response().setStatusCode(500)
                .putHeader("content-type", "application/json")
                .end(new JsonObject(JsonUtil.obj2Json(resps)).encodePrettily());
    }

    /**
     * Send back a response with status 500 Internal Error.
     *
     * @param context routing context
     * @param cause   error message
     */
    protected void internalError(RoutingContext context, String cause) {
        internalError(context, Resps.error(cause));
    }


    /**
     * Send back a response with status 400 Bad Request.
     *
     * @param context routing context
     * @param resps   message body
     */
    protected void badRequest(RoutingContext context, Resps resps) {

        context.response().setStatusCode(400)
                .putHeader("content-type", "application/json")
                .end(new JsonObject(JsonUtil.obj2Json(resps)).encodePrettily());
    }

    protected void badRequest(RoutingContext context) {
        badRequest(context, "");
    }

    protected void badRequest(RoutingContext context, String msg) {
        badRequest(context, Resps.fail(msg));
    }
}
